package org.example.mrrope.service;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * //包装车间派工单
 */
@Service
@Slf4j
public class PackagingWorkOrder {

    @Autowired
    private DingUtil dingUtil;

    public Integer savePackagingWorkOrder(JSONObject upJsonA, String id,String userId) throws Exception {
        //包装车间派工单
        String s = null;
        JSONObject upJsonB = new JSONObject();
        upJsonB.put("textField_lwt4miut", upJsonA.get("textField_lujgt578"));//客户名称
        upJsonB.put("textField_luga5zz1", upJsonA.get("textField_lwt4u8ls"));//订单SO号
        upJsonB.put("radioField_mann5ewv", upJsonA.has("radioField_makqj7pj")?upJsonA.get("radioField_makqj7pj"):"苍南");//生产工厂
        upJsonB.put("textField_m2u824xc", upJsonA.has("textField_m2e5ira7")?upJsonA.get("textField_m2e5ira7"):"/")                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           ;//PO
        upJsonB.put("textField_lwed3a24", "包装车间");//所属车间
        upJsonB.put("dateField_luga5zyz", upJsonA.has("dateField_m2wwkxdz") ? upJsonA.get("dateField_m2wwkxdz") : System.currentTimeMillis());//日期
        //for循环AC子表
        if (upJsonA.has("tableField_m0gbvy0a")) {
//            JSONArray jsonArrOne = upJsonA.getJSONArray("tableField_m0gbvy0a");
            List<String> list2 = new ArrayList<>();
            JSONArray jsonArrOne = dingUtil.getInnerTables(id,"FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW","tableField_m0gbvy0a");
            for (int i = 0; i < jsonArrOne.length(); i++) {
                JSONObject jsonObject = jsonArrOne.getJSONObject(i);
                String substring = jsonObject.getString("associationFormField_m0wbjlek_id").replaceAll("\\\\", "").substring(1);
                String instanceId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                double orderNumber = jsonObject.getDouble("numberField_m1hv1yu8");
                String acCode = jsonObject.getString("textField_m1kgb2td");
                if (instanceId != null) {
                    //AC表
                    String bomItem = dingUtil.getYidaById(instanceId);
                    JSONObject bomJsonObject = new JSONObject(bomItem);
                    //判断是不是仅采购
                    //获取工序
                    if (bomJsonObject.has("checkboxField_lx2luc3u")){
                        JSONArray gomxu = bomJsonObject.getJSONArray("checkboxField_lx2luc3u");
                        if (gomxu.toString().contains("仅采购")) {
                            if (!gomxu.toString().contains("包装")){
                                continue;
                            }
                        }
                    }else{
                        continue;
                    }
                    upJsonB.put("textField_lwt597ig", acCode);//产品编码 AC号
                    upJsonB.put("textField_lzcc6a1q", jsonObject.get("textField_m0xlus2q"));//产品名称
                    upJsonB.put("imageField_lwt597ic", bomJsonObject.has("imageField_lujgt57h") ? bomJsonObject.get("imageField_lujgt57h") : "");//成品图片
//                    upJsonB.put("numberField_lujhx4e3", bomJsonObject.has("numberField_lujhx4e3") ? bomJsonObject.get("numberField_lujhx4e3") : "");//内袋/盒装量？
                    upJsonB.put("numberField_lujhx4e3", bomJsonObject.has("numberField_lx41w1t2") ? bomJsonObject.get("numberField_lx41w1t2") : "");//内袋数量
                    upJsonB.put("numberField_lwt597ih", bomJsonObject.has("numberField_lwiynwwz") ? bomJsonObject.get("numberField_lwiynwwz") : "");//装量
                    upJsonB.put("textField_m2uama11", bomJsonObject.has("textField_lujgt577")?bomJsonObject.get("textField_lujgt577"):"");//客户货号
                    upJsonB.put("textareaField_mauymer2", bomJsonObject.has("textareaField_m1dtl54p")?bomJsonObject.get("textareaField_m1dtl54p"):"");//产品规格
                    upJsonB.put("textField_mcabwlnd", bomJsonObject.has("textField_m1dtl558")?bomJsonObject.get("textField_m1dtl558"):"");//内袋（盒）条码
                    upJsonB.put("textField_mcabwlne", bomJsonObject.has("textField_m1dtl559")?bomJsonObject.get("textField_m1dtl559"):"");//外箱条码
                    //箱数
                    Double numOne = 0.0;
                    //产品数量
                    Double numTow = 0.0;
                    if (jsonObject.has("numberField_m2aidy02")){
                        numTow = jsonObject.getDouble("numberField_m2aidy02");
                    }
                    if (jsonObject.has("numberField_m1hv1yu8")){
                        numOne = jsonObject.getDouble("numberField_m1hv1yu8");
                    }
                    upJsonB.put("numberField_lwt597ik", numOne);//总数量
                    upJsonB.put("numberField_lwt597ij", numTow);//箱数
//                    upJsonB.put("numberField_lwt597ik", jsonObject.has("numberField_m1hv1yu8") ? jsonObject.get("numberField_m1hv1yu8") : "");//总数量
//                    upJsonB.put("numberField_lwt597ij", jsonObject.has("numberField_m2aidy02") ? jsonObject.get("numberField_m2aidy02") : "");//箱数
                    upJsonB.put("numberField_m5qqg5lf", jsonObject.has("numberField_m5qo9bht") ? jsonObject.get("numberField_m5qo9bht") : "");//外箱装量
                    upJsonB.put("textareaField_lvxftd6b", bomJsonObject.has("textareaField_lvxftd6b") ? bomJsonObject.get("textareaField_lvxftd6b") : "");//包装方式
                    upJsonB.put("textareaField_lw61w5oe", bomJsonObject.has("textareaField_lw61w5oe") ? bomJsonObject.get("textareaField_lw61w5oe") : "");//备注
                    upJsonB.put("imageField_lujgt58p", bomJsonObject.has("imageField_lujgt58p") ? bomJsonObject.get("imageField_lujgt58p") : "");//外箱唛头 印刷内容图片
                    upJsonB.put("imageField_lujgt58q", bomJsonObject.has("imageField_lujgt58q") ? bomJsonObject.get("imageField_lujgt58q") : "");//产品吊牌 正反面图片
                    upJsonB.put("imageField_lujgt58r", bomJsonObject.has("imageField_lujgt58r") ? bomJsonObject.get("imageField_lujgt58r") : "");//产品吊牌悬挂位置
                    upJsonB.put("imageField_lvxhxh0b", bomJsonObject.has("imageField_lvxhxh0b") ? bomJsonObject.get("imageField_lvxhxh0b") : "");//外箱贴纸图片
                    upJsonB.put("imageField_lujgt58s", bomJsonObject.has("imageField_lujgt58s") ? bomJsonObject.get("imageField_lujgt58s") : "");//内袋贴纸图片
                    JSONArray bcp_upArray = new JSONArray();
                    JSONArray bc_upArray = new JSONArray();
                    //获取半成品
                    if (bomJsonObject.has("tableField_lwed3a1x")) {
//                        JSONArray bcp_Array = bomJsonObject.getJSONArray("tableField_lwed3a1x");
                        JSONArray bcp_Array = dingUtil.getInnerTables(instanceId,"FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K","tableField_lwed3a1x");
                        for (int j = 0; j < bcp_Array.length(); j++) {
                            JSONObject bcpUpJsonObj = new JSONObject();
                            JSONObject bcpJsonObj = bcp_Array.getJSONObject(j);
                            bcpUpJsonObj.put("textField_lujgt592", bcpJsonObj.get("textField_lujgt592"));//半成品货号
                            bcpUpJsonObj.put("textField_lwbmqipz", bcpJsonObj.get("textField_lwbmqipz"));//半成品名称
                            bcpUpJsonObj.put("textField_lujgt57g", bcpJsonObj.has("textareaField_m2ohpz46")?bcpJsonObj.get("textareaField_m2ohpz46"):"无");//品名规格
                            bcpUpJsonObj.put("numberField_lxvgkgg7", bcpJsonObj.has("numberField_lxvgkgg7")?bcpJsonObj.getDouble("numberField_lxvgkgg7"):0);//标准用量
                            bcpUpJsonObj.put("numberField_lxwv7czo", bcpJsonObj.has("numberField_lxvgkgg7")?bcpJsonObj.getDouble("numberField_lxvgkgg7") * numTow:0);//总应发量
                            bcpUpJsonObj.put("numberField_m5z1tmyo", bcpJsonObj.has("numberField_m5z1tmyo")?bcpJsonObj.getDouble("numberField_m5z1tmyo") * numTow:0);//实际总应发量
                            bcp_upArray.put(bcpUpJsonObj);
                        }
                    }
                    if (upJsonA.has("tableField_lxvknj7i")) {
//                        JSONArray bc_Array = upJsonA.getJSONArray("tableField_lxvknj7i");
                        JSONArray bc_Array = dingUtil.getInnerTables(id,"FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW","tableField_lxvknj7i");
                        for (int k = 0; k < bc_Array.length(); k++) {
                            JSONObject bcUpJsonObj = new JSONObject();
                            JSONObject bcJsonObj = bc_Array.getJSONObject(k);
                            if (bcJsonObj.getString("textField_m0gcswvr").equals(acCode)) {
                                bcUpJsonObj.put("textField_lxwy02u5", bcJsonObj.has("textField_lxvknj78")?bcJsonObj.getString("textField_lxvknj78"):"");
                                bcUpJsonObj.put("textField_lxwy02u6", bcJsonObj.has("textField_lxvknj79")?bcJsonObj.get("textField_lxvknj79"):"");//包材编号
                                bcUpJsonObj.put("textField_lxwy02u7", bcJsonObj.has("textField_lxvknj7a")?bcJsonObj.get("textField_lxvknj7a"):"");//规格描述
                                bcUpJsonObj.put("textField_lxwy02u8", bcJsonObj.has("textField_lxvknj7d")?bcJsonObj.get("textField_lxvknj7d"):"");//供应商
                                bcUpJsonObj.put("imageField_lxwy02u9", bcJsonObj.has("imageField_lxvknj7e") ? bcJsonObj.get("imageField_lxvknj7e") : "");//例图
                                bcUpJsonObj.put("textField_lxwy02ua", bcJsonObj.has("textField_lxvknj7h")?bcJsonObj.get("textField_lxvknj7h"):"");//备注
                                bcUpJsonObj.put("numberField_lxwy02ub", bcJsonObj.has("numberField_lz6f59g5")?bcJsonObj.get("numberField_lz6f59g5"):1);//标准用量
                                bcUpJsonObj.put("numberField_lxwy02uc", bcJsonObj.has("numberField_lxwv7czm")?bcJsonObj.get("numberField_lxwv7czm"):0);//应发量
                                bcUpJsonObj.put("numberField_m609uwf1", bcJsonObj.has("numberField_m4hx46fr")?bcJsonObj.get("numberField_m4hx46fr"):0);//实际应发量
//                                bcUpJsonObj.put("numberField_m2ucxjgr", bcJsonObj.has("numberField_lxwv7czm")?bcJsonObj.get("numberField_lxwv7czm"):0);//已下发作业总数
//                                bcUpJsonObj.put("numberField_m5f5gz4v", bcJsonObj.has("numberField_lxwv7czm")?bcJsonObj.get("numberField_lxwv7czm"):0);//未入库总数
//                                bcUpJsonObj.put("numberField_m5f5gz4x", bcJsonObj.has("numberField_lxwv7czm")?bcJsonObj.get("numberField_lxwv7czm"):0);//已上缴总数
                                bc_upArray.put(bcUpJsonObj);
                            }
                        }
                    }
                    //************生产计划*******************
                    String title = upJsonA.getString("textField_lwt4u8ls");
                    String fromUuid = "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW";
                    // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
                    JSONArray jsonArrayOne = FormUtils.getAssociationFormField(fromUuid, title, id);
                    upJsonB.put("associationFormField_m4tnw018", jsonArrayOne);
                    upJsonB.put("tableField_lwed3a1x", bcp_upArray);//半成品子表
                    upJsonB.put("tableField_lxwy02ud", bc_upArray);//包材子表
                    upJsonB.put("radioField_m42cd3fr", "正常");//派工单状态
//                    s = s + dingUtil.startInstance(upJsonB, "314764473436461353", "FORM-710F168856364416B7E566E252E82DCD2TYH");
                    JSONObject searchScheduleJson = new JSONObject();
                    searchScheduleJson.put("textField_luga5zz1",  upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//so号
                    searchScheduleJson.put("textField_lwt597ig", acCode);//AC号
                    String yiDaSearchReturnData_Schedule = dingUtil.yiDaSearchReturnData("FORM-2EF550E5EFC74A04927F791B7D515E35GTJK", searchScheduleJson);//获取包装派工单数据
                    JSONArray yiDaSearchReturnData_ScheduleJsonArray = new JSONArray(yiDaSearchReturnData_Schedule);
                    //-------------------------------新增并更新------------------------------
                    //如果有该派工单就更新，根据SO号，AC号判断
                    if (!yiDaSearchReturnData_ScheduleJsonArray.isEmpty()) {
                        String oid = yiDaSearchReturnData_ScheduleJsonArray.getJSONObject(0).getString("formInstanceId");
                        JSONObject zsObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                        Double todoAmount = upJsonA.has("numberField_lwt597ij") ? upJsonA.getDouble("numberField_lwt597ij") : 0.0;//应有的待完成量
                        Double finishedAmount = zsObject.has("numberField_m5f5gz4w") ? zsObject.getDouble("numberField_m5f5gz4w") : 0.0;//已完成量
                        Double dispatchedAmount = zsObject.has("numberField_m5f5gz4u") ? zsObject.getDouble("numberField_m5f5gz4u") : 0.0;//已下发量
                        Double receivedAmount = zsObject.has("numberField_m2ucxjgq") ? zsObject.getDouble("numberField_m2ucxjgq") : 0.0;//已入库量
                        upJsonB.put("numberField_m5f5gz4x", todoAmount - finishedAmount);//上缴
                        upJsonB.put("numberField_m2ucxjgr", todoAmount - dispatchedAmount);//未下发
                        upJsonB.put("numberField_m5f5gz4v", todoAmount - receivedAmount);//未入库
                        log.info("更新 包装车间派工单开始");
                        log.info("更新oid:{}", oid);
                        log.info("更新数据:{}", upJsonB);
                        dingUtil.UpdateYiDa(oid, upJsonB);//更新生产计划
                        log.info("更新 包装车间派工单完成");
                    }else{
                        upJsonB.put("numberField_m2ucxjgr", numTow);//未下发作业总数
                        upJsonB.put("numberField_m5f5gz4x", numTow);//未上缴总数
                        upJsonB.put("numberField_m5f5gz4v", numTow);//未入库总数
                        s = s + dingUtil.startInstance(upJsonB, userId, "FORM-2EF550E5EFC74A04927F791B7D515E35GTJK");
                    }
                }
                list2.add(acCode);
            }
            //查找现有的派工单，进行循环，多余的派工单删除
            //根据SO号搜索
            JSONObject paiGonJson = new JSONObject();
            paiGonJson.put("textField_luga5zz1", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//so号
            String yiDaPaiGonString = dingUtil.yiDaSearchReturnData("FORM-2EF550E5EFC74A04927F791B7D515E35GTJK", paiGonJson);//获取派工单数据
            JSONArray yiDaPaiGonJsonArray = new JSONArray(yiDaPaiGonString);
            HashMap<String, String> newMap = new HashMap<>();
            List<String> list1 = new ArrayList<>();
            //把AC号存在容器里面
            for (int i = 0; i < yiDaPaiGonJsonArray.length(); i++){
                String oid = yiDaPaiGonJsonArray.getJSONObject(i).getString("formInstanceId");
                JSONObject pgdObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                if (pgdObject.has("textField_lwt597ig")){
                    list1.add(pgdObject.getString("textField_lwt597ig"));
                    newMap.put(pgdObject.getString("textField_lwt597ig"),oid);
                }
            }
            // 找出派工单中有但生产计划中没有的元素
            // 派工单 减 生产计划 多出来的就是没用的派工单
            list1.removeAll(list2);
            if (list1.size() > 0){
                for (String numberA : list1) {
                    //删除多余的派工单
                    if (newMap.containsKey(numberA)){
                        JSONObject object = new JSONObject();
                        object.put("radioField_m42cd3fr", "暂停");
                        dingUtil.UpdateYiDa(newMap.get(numberA), object);
//                        dingUtil.delete(newMap.get(numberA));
                    }
                }
            }
            log.info("YIDA-startInstance--包装车间派工单生成流程结束" + s);
        }
        if (s == null) {
            return 1;
        } else {
            return 0;
        }
    }

    //刷新作业表
}
